package hzncc.wcs.modbus.service;

import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.exception.ModbusIOException;
import com.intelligt.modbus.jlibmodbus.exception.ModbusNumberException;
import com.intelligt.modbus.jlibmodbus.exception.ModbusProtocolException;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;


@Service
public class ModbusService {

    @Value("${modbus.host}")
    private String host;
    @Value("${modbus.port}")
    private int port;


    private ModbusMaster modbusMaster;

    public void init() throws ModbusIOException, UnknownHostException {
        //设置主机TCP参数
        TcpParameters tcpParameters = new TcpParameters();
        //设置TCP的IP地址
        InetAddress inetAddress = InetAddress.getByName(host);
        //TCP参数设置IP地址
        tcpParameters.setHost(inetAddress);
        //TCP设置长连接
        tcpParameters.setKeepAlive(true);
        //tcp设置端口,这里使用Modbus的默认端口502
        tcpParameters.setPort(Modbus.TCP_PORT);
        //创建一个主机
        modbusMaster = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
        //Modbus.setLogLevel(Modbus.LogLevel.LEVEL_DEBUG);
        //设置自增的id
        Modbus.setAutoIncrementTransactionId(true);

        if (!modbusMaster.isConnected()) {
            System.out.println("Modbus主机没有连接,现在建立连接");
            modbusMaster.connect();
        } else {
            System.out.println("Modbus主机已经连接");
        }
    }

//    public static void close() {
//        if (!modbusMaster.isConnected()) {
//            try {
//                modbusMaster.disconnect();
//            } catch (ModbusIOException e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }

//    @Resource
//    private static ModbusMaster modbusMaster;
//
        /**
         * "功能码0x04"
         * 读取HoldingRegister数据
         *
         * @param slaveId 寄存器地址ID
         * @param offset 寄存器读取开始地址
         * @param quantity 读取寄存器数量
         * @return int数组
         */
        public int[] readInputRegisters(int slaveId, int offset, int quantity) {
            try {
                return modbusMaster.readInputRegisters(slaveId, offset, quantity);
            } catch (ModbusProtocolException | ModbusNumberException | ModbusIOException e) {
                throw new RuntimeException(e);
            }
        }
        /**
         * "功能码0x03"
         * 读取HoldingRegister数据
         *
         * @param slaveId 寄存器地址ID
         * @param offset 寄存器读取开始地址
         * @param quantity 读取寄存器数量
         * @return int数组
         */
        public int[] readHoldingRegisters(int slaveId, int offset, int quantity) {
            try {
                return modbusMaster.readHoldingRegisters(slaveId, offset, quantity);
            } catch (ModbusProtocolException | ModbusNumberException | ModbusIOException e) {
                throw new RuntimeException(e);
            }
        }


    /**
     *
     * @param
     * @return 返回补零字符串
     */
    public String[] binaryListConversion(int[] ints) {
        int length = 8; // 假设我们想要所有二进制字符串长度为8
        // 使用Stream API转换并补位
        String[] binaryStrings = IntStream.of(ints)
                .mapToObj(number -> String.format("%" + length + "s", Integer.toBinaryString(number)).replace(' ', '0'))
                .toArray(String[]::new);

        System.out.println("转换后二进制数组:"+ binaryStrings);
        return binaryStrings;
    }

    /**
     *
     * @param
     * @return 返回补零字符串
     */
    public int[] binaryConversion(int str) {
        String string = IntStream.of(str).mapToObj(i -> Integer.toBinaryString(i)).toString();

        char[] chars = string.toCharArray();

        int[] intArray = new int[chars.length];
        for (int i = 0; i < chars.length; i++) {
            intArray[i] = chars[i] - '0';
        }

        System.out.println("转换后二进制数:"+ string);
        System.out.println("转换后char数组:"+ chars);
        System.out.println("转换后int数组:"+ intArray);

        return intArray;
    }
}
